package com.ssrs.framework.data;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ssrs.framework.data.properties.SqlLogProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus 配置
 *
 * @author ssrs
 */
@MapperScan("com.ssrs.*.mapper")
/** @Import(AutoConfiguredMapperScannerRegistrar.class) **/
@Configuration
public class MybatisPlusAutoConfiguration {

    @Autowired
    private SqlLogProperties sqlLogProperties;


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /**
         * 分页插件
         */
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        /**
         * 乐观锁插件
         */
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        /**
         * 自定义sql日志拦截器
         */
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }


    /**
     * 自动填充
     *
     * @return
     */
    @Bean
    public CommonMetaObjectHandler commonMetaObjectHandler() {
        return new CommonMetaObjectHandler();
    }

    /**
     * 自定义sql日志拦截器
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(
            name = {"sqlLog.enable"},
            havingValue = "true"
    )
    public MybatisSqlLogInterceptor mybatisSqlLogInterceptor() {
        MybatisSqlLogInterceptor mybatisSqlLogInterceptor = new MybatisSqlLogInterceptor();
        mybatisSqlLogInterceptor.setSqlLogProperties(sqlLogProperties);
        return mybatisSqlLogInterceptor;
    }


}
